package org.acceleo.fwk.dao.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.acceleo.fwk.dao.DaoException;

/**
 * Utility class to find a Database connection
 */
public class JdbcConnectionUtils {

	/**
	 * Configuration. Change here to map to your DB connexion
	 */
	private static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
	private static final String URL = "jdbc:derby:derbyDB;create=true";
	private static final String USER = "root";
	private static final String PASSWORD = "";
	
	
	private static JdbcConnectionUtils instance;

	/** 
	 * Lock to manage concurrency access
	 */
	private static Boolean initializationLock = new Boolean(true);


	/**
	 * Initialise the connection.
	 * @return a singleton 
	 * @throws DaoException
	 */
	public static JdbcConnectionUtils getInstance() throws DaoException {
		if (instance == null) {
			synchronized (initializationLock) {
				if (initializationLock.equals(Boolean.TRUE)) {
					instance = new JdbcConnectionUtils();
					initializationLock = new Boolean(false);
				}
			}
		}
		return instance;
	}

	/**
	 * Give a connection to the database.
	 * @return
	 * @throws DaoException
	 */
	public Connection getConnection() throws DaoException {	
		try {			
			Connection connection = DriverManager.getConnection(URL/*,USER, PASSWORD*/);
			return connection;			
		} catch (SQLException e) {
			throw new DaoException("Cannot get connection from DriverManager." + e);
		}
	}
	
	// ----    Privates methods ----
	
	/**
	 * This constructor is private to conform singleton pattern
	 * @throws DaoException
	 */
	private JdbcConnectionUtils() throws DaoException {
		try {
			Class.forName(DRIVER);						
		} catch (ClassNotFoundException e) {
			throw new DaoException("Init: Cannot init jdbc driver class " + e);
		}
	}
}